const { DataTypes } = require('sequelize');
const { sequelize } = require('../../config/database');
const { User } = require('./User');

const RechargeRecord = sequelize.define('recharge_record', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'user',
      key: 'id'
    }
  },
  orderNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    validate: {
      min: 0.01
    }
  },
  paymentMethod: {
    type: DataTypes.ENUM('alipay', 'wechat', 'bank_transfer', 'other'),
    allowNull: false
  },
  transactionId: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  status: {
    type: DataTypes.ENUM('pending', 'completed', 'failed', 'refunded'),
    defaultValue: 'pending'
  },
  paymentTime: {
    type: DataTypes.DATE,
    allowNull: true
  },
  remark: {
    type: DataTypes.STRING(255),
    allowNull: true
  }
}, {
  timestamps: true
});

// 建立与 User 模型的关联
RechargeRecord.belongsTo(User, { foreignKey: 'userId' });
User.hasMany(RechargeRecord, { foreignKey: 'userId' });

// 同步模型到数据库
const syncRechargeRecord = async (force = false) => {
  try {
    await RechargeRecord.sync({ force });
    console.log('RechargeRecord 模型同步成功');
  } catch (error) {
    console.error('RechargeRecord 模型同步失败:', error);
  }
};

module.exports = {
  RechargeRecord,
  syncRechargeRecord
};